package com.servlets;

import com.alibaba.fastjson.JSON;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@WebServlet("/Img.do")
public class ImgServlet extends BaseServlet{
    private static final String UPLOAD_PATH = "D:\\upload\\";
    private static final String RESPONSE = "{\n" +
            "  \"code\": 0\n" +
            "  ,\"msg\": \"\"\n" +
            "  ,\"data\": {\n" +
            "    \"src\": \"XXX\"\n" +
            "  }\n" +
            "} ";
    //图片上传方法
    public void uploadImg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //1.创建实例工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //2.使用工厂创建解析对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //3.设置编码格式
        fileUpload.setHeaderEncoding("utf-8");
        try {
            //4.使用解析器来解析对象
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            for (FileItem item : fileItems) {
                String name = UUID.randomUUID().toString().replace("-","").substring(0,15)+item.getName().substring(item.getName().lastIndexOf("."));
                if (!item.isFormField()){//判断是否是文件
                    //5.上传文
                    //6.将文件写入文件夹
                    item.write(new File(UPLOAD_PATH,name));
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write(RESPONSE.replace("XXX",name));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    //图片下载方法
    public void downloadImg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String fname = request.getParameter("fname");
        String filepath = UPLOAD_PATH+"/"+fname;
        System.out.println(filepath);
        //将指定路径下的文件引入到当前工程中的file对象中
        File file = new File(filepath);
        // 所有浏览器都会使用本地编码，即中文操作系统使用GBK,浏览器收到这个文件名后，会使用iso-8859-1来解码
        fname=new String(fname.getBytes("gbk"),"iso8859-1");
        //设置响应头以后，浏览器就会识别你的请求是下载文件,然后以下载的方式响应你,是访问资源还是下载资源关键就看有没有设置这个响应头
        response.addHeader("content-disposition", "attachment;filename=" + fname);
        if(!file.exists()) {
            response.getWriter().print("您要下载的文件不存在！");
            return;
        }
        //把输入流中的数据写到输出流中去
        IOUtils.copy(new FileInputStream(filepath),response.getOutputStream());
    }

    //图片显示方法
    public void showImg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  {
        String imgName = request.getParameter("name");
        File file = new File(UPLOAD_PATH+imgName);
        FileInputStream is = null;
        if (file.exists())
            is = new FileInputStream(file);
        else
            is = new FileInputStream(UPLOAD_PATH+"图片丢失.jpg");

        ServletOutputStream os = response.getOutputStream();
        IOUtils.copy(is,os);
    }
}
